package com.hll.api.controller.xinhua;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hll.api.config.web.RespMessage;
import com.hll.api.entity.Collect;
import com.hll.api.entity.User;
import com.hll.api.service.ICollectService;
import com.hll.api.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 收藏 前端控制器
 * </p>
 *
 * @author 何龙
 * @since 2019-06-25
 */
@RestController("xinhuaCollectController")
@RequestMapping("/api/xinhua")
public class CollectController {
	@Resource
	ICollectService service;
	@Resource
	UserService userService;

	@PostMapping("/collect")
	public RespMessage add(String goodsId, String name, String extension, HttpServletRequest request) {
		HttpSession session = request.getSession();
		User user = userService.getXinhuaUser(request);
		QueryWrapper<Collect> wrapper = new QueryWrapper<>();
		wrapper.eq("user_id", user.getId()).eq("goods_id", goodsId);
		Collect one = service.getOne(wrapper);
		if (one != null) {
			return RespMessage.error("您已经收藏过了");
		}
		Collect collect = new Collect();
		collect.setDate(new Date());
		collect.setUserId(user.getId().intValue());
		collect.setGoodsId(goodsId);
		collect.setName(name);
		collect.setExtension(extension);
		service.save(collect);
		return RespMessage.success("收藏成功");
	}

	@DeleteMapping("/collect/{goodsId}")
	public RespMessage del(HttpServletRequest request, @PathVariable String goodsId) {
		User user = userService.getXinhuaUser(request);
		QueryWrapper<Collect> wrapper = new QueryWrapper<>();
		wrapper.eq("user_id", user.getId()).eq("goods_id", goodsId);
		service.remove(wrapper);
		return RespMessage.success("移除收藏成功");
	}

	@GetMapping("/collect")
	public RespMessage get(HttpServletRequest request) {
		User user = userService.getXinhuaUser(request);
		if (user == null) {
			return RespMessage.loginError();
		}
		QueryWrapper<Collect> wrapper = new QueryWrapper<>();
		wrapper.eq("user_id", user.getId()).orderByDesc("date");
		List<Collect> list = service.list(wrapper);
		return RespMessage.success(list, "");
	}


	@GetMapping("/collect/{goodsId}")
	public RespMessage getCollect(@PathVariable String goodsId, HttpServletRequest request) {
		User user = userService.getXinhuaUser(request);
		if (user == null) {
			return RespMessage.loginError();
		}
		QueryWrapper<Collect> wrapper = new QueryWrapper<>();
		wrapper.eq("user_id", user.getId()).eq("goods_id", goodsId);
		Collect one = service.getOne(wrapper);
		return RespMessage.success(one!=null, null);

	}
}
